
/**
 * 加载组织机构下拉
 */
function queryDeptTree()
{
	var url = ctx + "system/dept/treeData";
	var options = {
        url: url,
        expandLevel: 4,
        onClick : zOnClick
    };
	$.tree.init(options);

	function zOnClick(event, treeId, treeNode) {
		 $("#dprtcode").val(treeNode.id);
		 $('#orgName').val(treeNode.name);
		 $.table.search();
		 $('.ztree').css('display','none');
	}

}

/**
 * 显示树
 */
function showTree(){
    if($('.ztree').css('display') == 'none'){
        $('.ztree').css('display','block'); 
    } else{
        $('.ztree').css('display','none'); 
    }
    $("body").bind("mousedown", onBodyDownByActionType); 
}
function onBodyDownByActionType(event) {  
    if (event.target.id.indexOf('treeDemo') == -1){  
        if(event.target.id != 'orgName'){
        } 
    }  
}



//var hasOperatingDepart=false; //列字段权限标识
/**
 * 
 * @param 日期减
 * @param days
 * @returns {String}
 */
function lessDate(date,days){ 
    var d=new Date(date); 
    d.setDate(d.getDate()-days); 
    var m=d.getMonth()+1; 
    var strDate = d.getDate();
    if (m >= 1 && m <= 9) {
        m = "0" + m;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    return d.getFullYear()+'-'+m+'-'+strDate; 
} 

/**
 * 
 * @param 日期减
 * @param days
 * @returns {String}
 */
function addDate(date,days){ 
	var d=new Date(date); 
	d.setMonth(d.getMonth()+parseInt(days)); 
	d.setDate(d.getDate()-1); 
	var strDate = d.getDate();
	var m=d.getMonth()+1; 
	if (m >= 1 && m <= 9) {
		m = "0" + m;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	
	return d.getFullYear()+'-'+m+'-'+strDate; 
}

// 主子表操作封装处理
var sub = {
	editColumn: function() {
		var count = $("#bootstrap-table").bootstrapTable('getData').length;
		var params = new Array();
		for (var dataIndex = 0; dataIndex <= count; dataIndex++) {
			var columns = $('#bootstrap-table tr[data-index="' + dataIndex + '"] td');
			var obj = new Object();
			for (var i = 0; i < columns.length; i++) {
				var inputValue = $(columns[i]).find('input');
				var selectValue = $(columns[i]).find('select');
				var key = $.table._option.columns[i].field;
				if ($.common.isNotEmpty(inputValue.val())) {
					obj[key] = inputValue.val();
				} else if ($.common.isNotEmpty(selectValue.val())) {
					obj[key] = selectValue.val();
				} else {
					obj[key] = "";
				}
			}
			params.push({ index: dataIndex, row: obj });
		}
		$("#bootstrap-table").bootstrapTable("updateRow", params);
	},
	delColumn: function(column) {
		sub.editColumn();
		var subColumn = $.common.isEmpty(column) ? "index" : column;
		var ids = $.table.selectColumns(subColumn);
		if (ids.length == 0) {
			$.modal.alertWarning("请至少选择一条记录");
			return;
		}
		$("#bootstrap-table").bootstrapTable('remove', { field: subColumn, values: ids });
	}
};

/**
 * 通用方法封装处理
 * Copyright (c) 2019 admin 
 */
$(function() {
	
	// select2复选框事件绑定
	if ($.fn.select2 !== undefined) {
		$("select.form-control:not(.noselect2)").each(function () {
			$(this).select2().on("change", function () {
				$(this).valid();
			})
		})
	}
	// checkbox 事件绑定
	if ($(".check-box").length > 0) {
	    $(".check-box").iCheck({
	    	checkboxClass: 'icheckbox-blue',
			radioClass: 'iradio-blue',
	    })
	}
	// radio 事件绑定
	if ($(".radio-box").length > 0) {
	    $(".radio-box").iCheck({
	    	checkboxClass: 'icheckbox-blue',
			radioClass: 'iradio-blue',
	    })
	}
	// laydate 时间控件绑定
	if ($(".select-time").length > 0) {
		layui.use('laydate', function() {
		    var laydate = layui.laydate;
		    var startDate = laydate.render({
		        elem: '#startTime',
		        max: $('#endTime').val(),
		        theme: 'molv',
		        trigger: 'click',
		        done: function(value, date) {
		            // 结束时间大于开始时间
		            if (value !== '') {
		                endDate.config.min.year = date.year;
		                endDate.config.min.month = date.month - 1;
		                endDate.config.min.date = date.date;
		            } else {
		                endDate.config.min.year = '';
		                endDate.config.min.month = '';
		                endDate.config.min.date = '';
		            }
		        }
		    });
		    var endDate = laydate.render({
		        elem: '#endTime',
		        min: $('#startTime').val(),
		        theme: 'molv',
		        trigger: 'click',
		        done: function(value, date) {
		            // 开始时间小于结束时间
		            if (value !== '') {
		                startDate.config.max.year = date.year;
		                startDate.config.max.month = date.month - 1;
		                startDate.config.max.date = date.date;
		            } else {
		                startDate.config.max.year = '';
		                startDate.config.max.month = '';
		                startDate.config.max.date = '';
		            }
		        }
		    });
		});
	}

	// laydate time-input 时间控件绑定
	if ($(".time-input1").length > 0) {
		layui.use('laydate', function() {
			var laydate = layui.laydate;
			var times = $(".time-input1");
			// 控制控件外观
			var type = times.attr("data-type") || 'date';
			// 控制回显格式
			var format = times.attr("data-format") || 'yyyy-MM-dd';
			for (var i = 0; i < times.length; i++) {
				var time = times[i];
				laydate.render({
					elem: time,
					theme: 'molv',
					trigger: 'click',
					type: type,
					format: format,
					done: function(value, date) {
						$("#nextTestDate").val(addDate(value,$("#testCycle").val()));
					}
				});
			}
		});
	}
	// laydate time-input 时间控件绑定
	if ($(".time-input").length > 0) {
	    layui.use('laydate', function() {
	        var laydate = layui.laydate;
	        var times = $(".time-input");
	        // 控制控件外观
	        var type = times.attr("data-type") || 'date';
	        // 控制回显格式
	        var format = times.attr("data-format") || 'yyyy-MM-dd';
	        for (var i = 0; i < times.length; i++) {
	            var time = times[i];
	            laydate.render({
	                elem: time,
	                theme: 'molv',
	                trigger: 'click',
	                type: type,
	                format: format,
	                done: function(value, date) {
	                }
	            });
	        }
	    });
	}
	// laydate time-input 时间控件绑定
	if ($(".time-input-times").length > 0) {
		layui.use('laydate', function() {
			var laydate = layui.laydate;
			var times = $(".time-input-times");
			// 控制控件外观
			var type = times.attr("data-type") || 'datetime';
			// 控制回显格式
			var format = times.attr("data-format") || 'yyyy-MM-dd HH:mm:ss';
			for (var i = 0; i < times.length; i++) {
				var time = times[i];
				laydate.render({
					elem: time,
					theme: 'molv',
					trigger: 'click',
					type: type,
					format: format,
					done: function(value, date) {
						console.info(value);
					}
				});
			}
		});
	}
	
	// tree 关键字搜索绑定
	if ($("#keyword").length > 0) {
		$("#keyword").bind("focus", function focusKey(e) {
		    if ($("#keyword").hasClass("empty")) {
		        $("#keyword").removeClass("empty");
		    }
		}).bind("blur", function blurKey(e) {
		    if ($("#keyword").val() === "") {
		        $("#keyword").addClass("empty");
		    }
		    $.tree.searchNode(e);
		}).bind("input propertychange", $.tree.searchNode);
	}
	// tree表格树 展开/折叠
	var expandFlag;
	$("#expandAllBtn").click(function() {
		var dataExpand = $.common.isEmpty($.table._option.expandAll) ? true : $.table._option.expandAll;
		expandFlag = $.common.isEmpty(expandFlag) ? dataExpand : expandFlag;
	    if (!expandFlag) {
	        $('#' + $.table._option.id).bootstrapTreeTable('expandAll');
	    } else {
	        $('#' + $.table._option.id).bootstrapTreeTable('collapseAll');
	    }
	    expandFlag = expandFlag ? false: true;
	})
});

/** 刷新选项卡 */
var refreshItem = function(){
    var topWindow = $(window.parent.document);
	var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-id');
	var target = $('.Stm_iframe[data-id="' + currentId + '"]', topWindow);
    var url = target.attr('src');
    target.attr('src', url).ready();
}

/** 关闭选项卡 */
var closeItem = function(){
	var topWindow = $(window.parent.document);
	var panelUrl = window.frameElement.getAttribute('data-panel');
	$('.page-tabs-content .active i', topWindow).click();
	if($.common.isNotEmpty(panelUrl)){
		$('.menuTab[data-id="' + panelUrl + '"]', topWindow).addClass('active').siblings('.menuTab').removeClass('active');
		$('.mainContent .Stm_iframe', topWindow).each(function() {
            if ($(this).data('id') == panelUrl) {
                $(this).show().siblings('.Stm_iframe').hide();
                return false;
            }
		});
	}
}

/** 创建选项卡 */
function createMenuItem(dataUrl, menuName) {
	var panelUrl = window.frameElement.getAttribute('data-id');
    dataIndex = $.common.random(1,100),
    flag = true;
    if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false;
    var topWindow = $(window.parent.document);
    // 选项卡菜单已存在
    $('.menuTab', topWindow).each(function() {
        if ($(this).data('id') == dataUrl) {
            if (!$(this).hasClass('active')) {
                $(this).addClass('active').siblings('.menuTab').removeClass('active');
                $('.page-tabs-content').animate({ marginLeft: ""}, "fast");
                // 显示tab对应的内容区
                $('.mainContent .Stm_iframe', topWindow).each(function() {
                    if ($(this).data('id') == dataUrl) {
                        $(this).show().siblings('.Stm_iframe').hide();
                        return false;
                    }
                });
            }
            flag = false;
            return false;
        }
    });
    // 选项卡菜单不存在
    if (flag) {
        var str = '<a href="javascript:;" class="active menuTab" data-id="' + dataUrl + '" data-panel="' + panelUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
        $('.menuTab', topWindow).removeClass('active');

        // 添加选项卡对应的iframe
        var str1 = '<iframe class="Stm_iframe" name="iframe' + dataIndex + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" data-panel="' + panelUrl + '" seamless></iframe>';
        $('.mainContent', topWindow).find('iframe.Stm_iframe').hide().parents('.mainContent').append(str1);
        
        window.parent.$.modal.loading("数据加载中，请稍后...");
        $('.mainContent iframe:visible', topWindow).load(function () {
        	window.parent.$.modal.closeLoading();
        });

        // 添加选项卡
        $('.menuTabs .page-tabs-content', topWindow).append(str);
    }
    return false;
}

//日志打印封装处理
var log = {
    log: function (msg) {
    	console.log(msg);
    },
    info: function(msg) {
    	console.info(msg);
    },
    warn: function(msg) {
    	console.warn(msg);
    },
    error: function(msg) {
    	console.error(msg);
    }
};

/** 设置全局ajax处理 */
$.ajaxSetup({
    complete: function(XMLHttpRequest, textStatus) {
        if (textStatus == 'timeout') {
            $.modal.alertWarning("服务器超时，请稍后再试！");
            $.modal.closeLoading();
        } else if (textStatus == "parsererror") {
            $.modal.alertWarning("服务器错误，请联系管理员！");
            $.modal.closeLoading();
        }
    }
});
layer.config({
    extend: 'moon/style.css',
    skin: 'layer-ext-moon'
});



